package com.cjd.view;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;

import com.cjd.common.R;
import com.cjd.common.utils.BitmapUtil;

import java.util.Arrays;
import java.util.List;

/**
 * @Author chenjidong
 * @email 374122600@qq.com
 * created 2019/6/12
 * description 电池充电流程
 */
public class BatteryChargeProgressView extends View {
    private Paint backgroundPaint, currentPaint, linePaint, textPaint;
    private float density;

    // view 的宽高
    private int viewWidth, viewHeight;
    private int radius;
    private int num = 4;

    private ValueAnimator angleAnimator;
    private int startAngle;//动画角度
    private String[] textArrays;
    private Bitmap[] icons;
    private int backgroundColor, lineColor, activeColor;
    private int activePosition;

    public BatteryChargeProgressView(Context context) {
        super(context);
    }

    public BatteryChargeProgressView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public BatteryChargeProgressView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        density = context.getResources().getDisplayMetrics().density;
        textArrays = context.getResources().getStringArray(R.array.recharge_progress_list);
        backgroundColor = Color.parseColor("#55FFFFFF");
        lineColor = backgroundColor;
        activeColor = Color.WHITE;

        if (attrs != null) {
            TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.BatteryChargeProgressView);
            backgroundColor = ta.getColor(R.styleable.BatteryChargeProgressView_background_color, backgroundColor);
            lineColor = ta.getColor(R.styleable.BatteryChargeProgressView_line_color, lineColor);
            activeColor = ta.getColor(R.styleable.BatteryChargeProgressView_active_color, activeColor);
            ta.recycle();
        }

        backgroundPaint = new Paint();
        backgroundPaint.setStyle(Paint.Style.FILL);
        backgroundPaint.setColor(backgroundColor);
        backgroundPaint.setAntiAlias(true);

        currentPaint = new Paint();
        currentPaint.setStyle(Paint.Style.STROKE);
        currentPaint.setStrokeWidth(5);
        currentPaint.setAntiAlias(true);
        currentPaint.setColor(activeColor);

        textPaint = new Paint(currentPaint);
        textPaint.setStrokeWidth(1);
        textPaint.setStyle(Paint.Style.FILL);
        textPaint.setTextSize(dp2px(12));
        textPaint.setAntiAlias(true);//抗锯齿
        textPaint.setTextAlign(Paint.Align.CENTER);//基线剧中

        linePaint = new Paint(backgroundPaint);
        linePaint.setStyle(Paint.Style.STROKE);
        textPaint.setAntiAlias(true);
        linePaint.setStrokeWidth(8);
        linePaint.setColor(lineColor);


        angleAnimator = ValueAnimator.ofInt(0, 360);
        angleAnimator.setRepeatCount(ValueAnimator.INFINITE);
        angleAnimator.setInterpolator(new LinearInterpolator());
        angleAnimator.setDuration(1000);
        angleAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                startAngle = (int) animation.getAnimatedValue();
                invalidate();
            }
        });

        initIcons(context);
        setActivePosition(0);
    }

    private void initIcons(Context context) {
        int wh = dp2px(48);
        Bitmap bitmap = BitmapUtil.compressByResId(context.getResources(), R.drawable.base_ic_lightning, wh, wh);
        Bitmap bitmap1 = BitmapUtil.compressByResId(context.getResources(), R.drawable.base_ic_rise, wh, wh);
        Bitmap bitmap2 = BitmapUtil.compressByResId(context.getResources(), R.drawable.base_ic_circle, wh, wh);
        Bitmap bitmap3 = BitmapUtil.compressByResId(context.getResources(), R.drawable.base_ic_finish, wh, wh);

        icons = new Bitmap[]{bitmap, bitmap1, bitmap2, bitmap3};

    }

    /**
     * 重新计算大小
     */
    private void afreshClipIcon() {
        if (viewHeight <= 0)
            return;
        radius = viewHeight / 4;

        int width = (radius * 2) / 4 * 2;//圆周长的 4/3

        if (icons != null && icons.length > 0) {
            List<Bitmap> bitmapList = Arrays.asList(icons);
            for (int i = 0; i < bitmapList.size(); i++) {
                icons[i] = BitmapUtil.matrixScale(bitmapList.get(i), 0, 0, width, width);
            }
        }
    }


    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        afreshClipIcon();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        if (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.UNSPECIFIED) {
            viewWidth = MeasureSpec.getSize(widthMeasureSpec);
        } else
            viewWidth = getResources().getDisplayMetrics().widthPixels;

        if (MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.UNSPECIFIED) {
            viewHeight = MeasureSpec.getSize(heightMeasureSpec);
        } else
            viewHeight = viewWidth > 0 ? viewWidth / 2 : dp2px(150);//默认高度
    }

    @SuppressLint("DrawAllocation")
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        radius = viewHeight / 4;
        int lineWidth = radius;
        int start = (viewWidth - radius * ((num * 2) + (num - 1))) / 2;

        for (int i = 0; i < num; i++) {

            //绘制背景
            float circleCenterX = start + radius * (i + 1) + radius * i + lineWidth * i;
            float circleCenterY = viewHeight / 2f;
            canvas.drawCircle(circleCenterX, circleCenterY, radius, backgroundPaint);

            //绘制间隔线
            if (i > 0 && i <= (num - 1)) {
                float circumference = radius * 2;
                float startX = start + circumference * i + lineWidth * (i - 1);

                float stopX = startX + lineWidth;
                canvas.drawLine(startX, circleCenterY, stopX, circleCenterY, linePaint);
            }

            if (i == activePosition) {//绘制选中的动画
                float activeLeft = circleCenterX - radius;
                float activeTop = circleCenterY - radius;
                float activeRight = circleCenterX + radius;
                float activeBottom = circleCenterY + radius;
                RectF activeRectF = new RectF(activeLeft, activeTop, activeRight, activeBottom);
                canvas.drawArc(activeRectF, startAngle, 350, false, currentPaint);
            }

            //计算文字宽高
            String text = getText(i);
            if (!TextUtils.isEmpty(text)) {
                float textWidth = textPaint.measureText(text);
                Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
                float textHeight = fontMetrics.bottom - fontMetrics.top;

                canvas.drawText(text, circleCenterX - textWidth / 2 + radius, circleCenterY + textHeight + radius, textPaint);
            }

            //绘制图标
            Bitmap icon = getIcon(i);
            if (icon != null) {
                Rect src = new Rect(0, 0, icon.getWidth(), icon.getHeight());
                int dstLeft = (int) (circleCenterX - icon.getWidth() / 2);
                int dstTop = (int) (circleCenterY - icon.getHeight() / 2);
                int dstRight = (int) (circleCenterX - icon.getWidth() / 2) + icon.getWidth();
                int dstBottom = (int) (circleCenterY - icon.getHeight() / 2) + icon.getHeight();
                Rect dst = new Rect(dstLeft, dstTop, dstRight, dstBottom);
                canvas.drawBitmap(icon, src, dst, textPaint);
            }
        }
    }

    /**
     * 获取文字
     */
    private String getText(int i) {
        if (textArrays != null && textArrays.length - 1 >= i)
            return textArrays[i];
        return null;
    }

    /**
     * 获取 icon
     *
     * @param i 根据下标 读取对应icon
     * @return null 不显示
     */
    private Bitmap getIcon(int i) {
        if (icons != null && icons.length - 1 >= i) {
            return icons[i];
        }
        return null;
    }

    public void setNum(int num) {
        this.num = num;
    }

    @Override
    public void setBackgroundColor(int backgroundColor) {
        this.backgroundColor = backgroundColor;
    }

    public void setLineColor(int lineColor) {
        this.lineColor = lineColor;
    }

    public void setActiveColor(int activeColor) {
        this.activeColor = activeColor;
    }

    /**
     * 负数表示 取消激活 位置
     *
     * @param activePosition 默认 0
     */
    public void setActivePosition(int activePosition) {
        if (angleAnimator != null && !angleAnimator.isStarted())
            angleAnimator.start();

        this.activePosition = activePosition;
    }

    /**
     * 根据当前电池电量 计算
     *
     * @param scale 当前电量
     */
    public void setBatteryPowerScale(int scale) {
        if (scale >= 100) {
            setActivePosition(num - 1);
        } else if (scale >= 80)
            setActivePosition(num - 2);
        else if (scale >= 50)
            setActivePosition(num - 3);
        else
            setActivePosition(0);
    }

    public void setIcons(Bitmap[] icons) {
        this.icons = icons;
    }

    public void setTextArrays(String[] textArrays) {
        this.textArrays = textArrays;
    }

    public int dp2px(float dp) {
        return (int) (dp * density + 0.5f);
    }


}
